import React, { Component, useRef } from 'react'
import { SearchOutlined } from "@ant-design/icons";
import { Form, Input, Space, Button, Select, Switch } from "antd";
import _ from 'lodash';
import TheButton from '@/components/TheButton';
import TheTable from '@/components/TheTable';
import ThePagination from '@/components/ThePagination';
import TheDialog from '@/components/TheDialog';
import TheUpload from '@/components/TheUpload';
import TheImage from '@/components/TheImage';
import { apiGetVehiclePage, apiGetChauffeurPage, apiGetVehicleAdd, apiGetVehicleDel, apiGetVehicleEdit } from '@/request/petTaxi';

const SearchHeader = ({ openDialog, getValue }) => {
  const formRef = useRef()
  const onFinish = (values) => {
    _.forIn(values, (v, k) => {
      if (!v) {
        delete (values[k])
      }
    })
    getValue(values)
  }
  const reset = () => {
    formRef.current.setFieldsValue({
      storeVehicleId: '',
      plateNumber: ''
    })
    getValue({})
  }
  return (
    <div
      className="p-search-box"
      style={{ display: "flex", justifyContent: "space-between" }}
    >
      <Form ref={formRef} onFinish={onFinish} layout="inline">
        <Form.Item name="storeVehicleId">
          <Input suffix={<SearchOutlined />} placeholder={"请输入车辆ID"} />
        </Form.Item>
        <Form.Item name="plateNumber">
          <Input suffix={<SearchOutlined />} placeholder={"请输入车牌号"} />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button htmlType="submit" type="primary">搜索</Button>
            <Button onClick={reset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>
      <TheButton haspermi={['taxi:car:add']} type="default" size="middle" onClick={openDialog}>
        新增车辆
      </TheButton>
    </div>
  );
};


export default class Car extends Component {
  state = {
    columns: [
      {
        title: '车辆ID',
        dataIndex: 'storeVehicleId',
        key: 'storeVehicleId'
      },
      {
        title: '车辆图片',
        dataIndex: 'vehicleImage',
        key: 'vehicleImage',
        render: (text, record) => {
          return <TheImage src={text || ''} width={100} height={60} />
        }
      },
      {
        title: '车辆品牌',
        dataIndex: 'vehicleBrand',
        key: 'vehicleBrand'
      },
      {
        title: '车辆型号',
        dataIndex: 'vehicleModels',
        key: 'vehicleModels'
      },
      {
        title: '车身颜色',
        dataIndex: 'vehicleColor',
        key: 'vehicleColor'
      },
      {
        title: '车牌号',
        dataIndex: 'plateNumber',
        key: 'plateNumber'
      },
      {
        title: '司机',
        dataIndex: 'storeChauffeurName',
        key: 'storeChauffeurName'
      },
      {
        title: '状态',
        dataIndex: 'chauffeurStatus',
        key: 'chauffeurStatus',
        render: (text, record) => {
          let label = '';
          switch (text) {
            case 'Y':
              label = '繁忙';
              break;
            case 'N':
              label = '空闲';
              break;
            case 'X':
              label = '休息';
              break;
          }
          return label;
        }
      },
      {
        title: '车辆状态',
        dataIndex: 'chauffeurStatus',
        key: 'chauffeurStatus',
        render: (text, record) => {
          return <Switch disabled={text !== 'X'} onChange={() => this.changeStatus(record)} checkedChildren="激活" unCheckedChildren="休息" checked={text !== 'X'} />
        }
      },
      {
        title: '操作',
        fixed: 'right',
        render: (text, record) => {
          return <>
            <TheButton haspermi={['taxi:car:edit']} onClick={() => this.editDialog(record)}>编辑</TheButton>
            <TheButton haspermi={['taxi:car:delete']} onClick={() => this.delConfirm(record.storeVehicleId)}>删除</TheButton>
          </>
        }
      },
    ],
    dataSource: [1],
    pageData: {
      pageNo: 1,
      pageSize: 10
    },
    total: 0,
    loading: false,
    searchValue: {},
    title: '新增车辆',
    visible: false,
    driverList: [],
    storeVehicleId: '',
    editValue: {},
    btnLoading: false
  }
  componentDidMount() {
    this.getData()
    this.getDriverList()
  }
  getData = async () => {
    this.setState({ loading: true })
    const { pageData, searchValue } = this.state
    let res = await apiGetVehiclePage({ ...pageData, ...searchValue })
    if (res.data && res.code === 0) {
      this.setState({
        dataSource: res.data,
        pageData: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        total: res.totalCount
      })
    }
    this.setState({ loading: false })
  }
  getDriverList = async () => {
    let res = await apiGetChauffeurPage({ pageNo: 1, pageSize: 1000 })
    if (res.data && res.code === 0) {
      let driverList = res.data.map(v => {
        return {
          label: v.chauffeurName,
          value: v.storeChauffeurId
        }
      })
      this.setState({
        driverList
      })
    }
  }
  getValue = value => {
    this.setState({
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      searchValue: value
    }, () => this.getData())
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo,
        pageSize
      }
    }, () => this.getData())
  }
  openDialog = () => {
    this.setState({
      visible: true,
      title: '新增车辆'
    })
  }
  editDialog = (value) => {
    this.setState({
      editValue: value,
      storeVehicleId: value.storeVehicleId,
      visible: true,
      title: '编辑车辆',
      fileList: [
        {
          uid: 1,
          name: 'image',
          status: 'done',
          url: value.vehicleImage
        }
      ]
    })
  }
  closeDialog = () => {
    this.setState({
      editValue: {},
      visible: false,
      title: '新增车辆',
      storeVehicleId: '',
      fileList: []
    })
  }
  saveCar = async value => {
    const { storeVehicleId } = this.state
    this.setState({ btnLoading: true })
    if (!storeVehicleId) {
      let res = await apiGetVehicleAdd({ ...value })
      if (res.code === 0) {
        React.$message({
          type: 'info',
          content: '新增成功'
        })
        this.closeDialog()
        this.getData()
      }
    } else {
      let res = await apiGetVehicleEdit({ storeVehicleId, ...value })
      if (res.code === 0) {
        React.$message({
          type: 'info',
          content: '修改成功'
        })
        this.closeDialog()
        this.getData()
      }
    }
    this.setState({ btnLoading: false })
  }
  delConfirm = (storeVehicleId) => {
    React.$confirm({
      title: '您确认删除此车辆信息吗？',
      onOk: async () => {
        let res = await apiGetVehicleDel({ storeVehicleId })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '删除成功'
          })
          this.getData()
        }
      }
    })
  }
  getFileResult = value => {
    if (value && value.length) {
      let arr = value.map(v => {
        let data = ''
        if (v.response && v.response.code === 0) {
          data = v.response.data
        }
        return data
      })
      let vehicleImage = arr.join(',')
      this.formRef.setFieldsValue({
        vehicleImage
      })
    }
  }
  changeStatus = (value) => {
    const { chauffeurStatus, storeVehicleId } = value
    let label = chauffeurStatus === 'X' ? '激活' : '休息'
    let status = chauffeurStatus !== 'X' ? 'X' : 'N'
    React.$confirm({
      title: `您确认${label}该车辆吗？`,
      onOk: async () => {
        let res = await apiGetVehicleEdit({ storeVehicleId, chauffeurStatus: status })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: `${label}成功`
          })
          this.getData()
        }
      }
    })
  }

  render() {
    const { columns, dataSource, loading, pageData: { pageNo, pageSize }, total, title, visible, editValue, fileList, driverList, btnLoading } = this.state
    return (
      <div className='p-layout-box'>
        <SearchHeader getValue={this.getValue} openDialog={this.openDialog} scroll={{ x: 'max-content', y: '63vh' }} />
        <div className="p-layout-content-pagination">
          <TheTable columns={columns} dataSource={dataSource} loading={loading} scroll={{ x: 'max-content', y: '63vh' }} />
          <ThePagination pageNo={pageNo} pageSize={pageSize} total={total} pageChange={this.pageChange} />
        </div>
        <TheDialog
          width={400}
          title={title}
          visible={visible}
          footer={null}
          handleCancel={this.closeDialog}
        >
          <Form labelCol={{ span: 6 }} labelAlign="left" ref={ref => this.formRef = ref} onFinish={this.saveCar} initialValues={editValue}>
            <Form.Item label="车辆图片" name={'vehicleImage'} rules={[{ required: true }]}>
              <TheUpload getFileResult={this.getFileResult} maxSize={10} len={1} fileList={fileList} />
            </Form.Item>
            <Form.Item label="车辆品牌" name={'vehicleBrand'} rules={[{ required: true }]}>
              <Input placeholder='请输入车辆品牌' />
            </Form.Item>
            <Form.Item label="车辆型号" name={'vehicleModels'} rules={[{ required: true }]}>
              <Input placeholder='请输入车辆型号' />
            </Form.Item>
            <Form.Item label="车身颜色" name={'vehicleColor'} rules={[{ required: true }]}>
              <Input placeholder='请输入车身颜色' />
            </Form.Item>
            <Form.Item label="车牌号" name={'plateNumber'} rules={[{ required: true }]}>
              <Input placeholder='请输入车牌号' />
            </Form.Item>
            <Form.Item label="司机" name={'storeChauffeurId'} rules={[{ required: true }]}>
              <Select options={driverList} placeholder='请选择司机' />
            </Form.Item>
            <Form.Item>
              <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: -30 }}>
                <Space>
                  <Button onClick={this.closeDialog}>取消</Button>
                  <Button loading={btnLoading} type='primary' htmlType='submit'>保存</Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </TheDialog>
      </div>
    )
  }
}
